package com.zhuozhou.jdyc.util.update.server;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.zhuozhou.jdyc.api.ConstantsHelper;
import com.zhuozhou.jdyc.util.log.ToastUtils;
import com.zhuozhou.jdyc.util.update.RxNet;
import com.zhuozhou.jdyc.util.update.UpdateManger;
import com.zhuozhou.jdyc.util.update.util.UpdateNotificationApkUtil;

import java.io.File;

/**
 * Created by 方舟 on 2017/10/17.
 * describe：更新下载广播接收器
 */
public class DownloadApkReceiver extends BroadcastReceiver {

    private UpdateNotificationApkUtil mNotificationUtil;
    public final static String NOTIFY_ID = "id";
    public final static String PROGRESS_RATE = "finished";
    public final static String APK_FILE_PATH = "filePath";
    public final static String IS_DOWNLOAD_APK = "isDownloadApk";

    public boolean isDownloadApk = false;

    @Override
    public void onReceive(Context context, Intent intent) {
        mNotificationUtil = UpdateNotificationApkUtil.getInstance();
        isDownloadApk = intent.getBooleanExtra(IS_DOWNLOAD_APK, false);
        if (RxNet.ACTION_START.equals(intent.getAction())) {
            if(isDownloadApk) {
                ConstantsHelper.isDownLoadApk = true;
            }
            // 下载开始的时候启动通知栏
            mNotificationUtil.showNotification(intent.getIntExtra(NOTIFY_ID, 0));
        } else if (RxNet.ACTION_UPDATE.equals(intent.getAction())) {
            // 更新进度条
            mNotificationUtil.updateNotification(intent.getIntExtra(NOTIFY_ID, 0),
                    intent.getIntExtra(PROGRESS_RATE, 0), "");
        } else if (RxNet.ACTION_FINISHED.equals(intent.getAction())) {
            mNotificationUtil.cancelNotification(intent.getIntExtra(NOTIFY_ID, 0));
            String filePath = intent.getStringExtra(APK_FILE_PATH);
            if (isDownloadApk) {
                ConstantsHelper.isDownLoadApk = false;
                UpdateManger.installApk(context, new File(filePath == null ? (RxNet.PATH + ConstantsHelper.APK_NAME) : filePath));
            } else {
                ToastUtils.showShort(context, "文件已保存至" + filePath);
            }
        } else if (RxNet.ACTION_CANCEL.equals(intent.getAction())) {
            if (isDownloadApk) {
                ConstantsHelper.isDownLoadApk = false;
            }
            mNotificationUtil.cancelNotification(intent.getIntExtra(NOTIFY_ID, 0));
        } else if (RxNet.ACTION_ERROR.equals(intent.getAction())) {
            if (isDownloadApk) {
                ConstantsHelper.isDownLoadApk = false;
            }
            ToastUtils.showShort(context, "下载错误" );
            mNotificationUtil.cancelNotification(intent.getIntExtra(NOTIFY_ID, 0));
        }
    }
}
